import { useJsonTable } from '@/hooks/tools/useJsonTable';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import CodeMirrorWrapper from '@/components/CodeMirrorWrapper';
import { 
  Alert,
  Box, 
  Button, 
  Chip,
  Divider, 
  Grid, 
  Paper, 
  Snackbar, 
  Stack,
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Typography,
  alpha
} from '@mui/material';
import { useState } from 'react';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
import TableViewIcon from '@mui/icons-material/TableView';
import DataObjectIcon from '@mui/icons-material/DataObject';

const JsonTablePage = () => {
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');

  const { 
    jsonInput, 
    setJsonInput, 
    tableData, 
    error, 
    parseJson, 
    copyAsCSV, 
    copyAsMarkdown, 
    copyAsHTML, 
    loadExample,
    copyAsExcel
  } = useJsonTable();

  const handleCopy = (format: 'csv' | 'markdown' | 'html' | 'excel') => {
    let success = false;
    let formatName = '';

    switch (format) {
      case 'csv':
        success = copyAsCSV();
        formatName = 'CSV';
        break;
      case 'markdown':
        success = copyAsMarkdown();
        formatName = 'Markdown';
        break;
      case 'html':
        success = copyAsHTML();
        formatName = 'HTML';
        break;
      case 'excel':
        success = copyAsExcel();
        formatName = 'Excel';
        break;
    }

    if (success) {
      setSnackbarMessage(`已复制为${formatName}格式`);
      setSnackbarOpen(true);
    }
  };

  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
  };

  return (
    <ToolPageTemplate 
      title="JSON 表格转换"
      description="将JSON数据转换为表格格式，支持复制为CSV、Markdown、Excel或HTML格式"
      category="格式转换"
      categoryColor="#FF9C6E"
    >
      {/* 快速信息区域 */}
      <Box sx={{ mb: 4 }}>
        <Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
          <Chip 
            icon={<DataObjectIcon />} 
            label="JSON转换" 
            variant="outlined" 
            color="primary"
          />
          <Chip 
            icon={<TableViewIcon />} 
            label="表格展示" 
            variant="outlined" 
            color="secondary"
          />
        </Stack>
      </Box>

      <Stack spacing={4}>
        {/* 编辑器部分 */}
        <Paper 
          elevation={0} 
          sx={{ 
            p: 3, 
            borderRadius: 3, 
            border: '1px solid', 
            borderColor: 'divider',
            width: '100%'
          }}
        >
          <Box sx={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center',
            mb: 3 
          }}>
            <Typography 
              variant="h6" 
              sx={{ 
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 1
              }}
            >
              <DataObjectIcon color="primary" />
              JSON 编辑器
            </Typography>
            <Button
              variant="text"
              size="small"
              startIcon={<AutoFixHighIcon />}
              onClick={loadExample}
              sx={{ 
                textTransform: 'none',
                fontWeight: 600,
                color: 'primary.main',
                '&:hover': {
                  bgcolor: 'primary.main',
                  color: 'primary.contrastText'
                }
              }}
            >
              加载示例
            </Button>
          </Box>

          <Box sx={{ borderRadius: 2, overflow: 'hidden', border: '1px solid', borderColor: 'divider', mb: 3 }}>
            <CodeMirrorWrapper
              label=""
              value={jsonInput}
              onChange={setJsonInput}
              height="300px"
              language="json"
              placeholder="请输入JSON数据..."
            />
          </Box>

          <Box sx={{ textAlign: 'center' }}>
            <Button 
              variant="contained" 
              size="large"
              onClick={parseJson}
              startIcon={<PlayArrowIcon />}
              sx={{ 
                borderRadius: '25px',
                px: 4,
                py: 1.5,
                textTransform: 'none',
                fontWeight: 600,
                fontSize: '1.1rem'
              }}
            >
              转换为表格
            </Button>
          </Box>
        </Paper>

        {/* 表格结果 */}
        {tableData && (
          <Paper 
            elevation={0} 
            sx={{ 
              p: 3, 
              borderRadius: 3, 
              border: '1px solid', 
              borderColor: 'divider',
              width: '100%'
            }}
          >
            <Typography 
              variant="h6" 
              sx={{ 
                mb: 3, 
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 1
              }}
            >
              <TableViewIcon color="primary" />
              表格结果
            </Typography>

            <TableContainer 
              component={Paper} 
              elevation={0}
              sx={{ 
                mb: 3, 
                maxHeight: 400,
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 2
              }}
            >
              <Table stickyHeader size="small">
                <TableHead>
                  <TableRow>
                    {tableData.headers.map((header, index) => (
                      <TableCell 
                        key={index}
                        sx={{ 
                          bgcolor: alpha('#9c27b0', 0.1),
                          fontWeight: 600,
                          color: '#9c27b0'
                        }}
                      >
                        {header}
                      </TableCell>
                    ))}
                  </TableRow>
                </TableHead>
                <TableBody>
                  {tableData.rows.map((row, rowIndex) => (
                    <TableRow 
                      key={rowIndex}
                      sx={{ 
                        '&:nth-of-type(odd)': { 
                          bgcolor: alpha('#9c27b0', 0.02) 
                        },
                        '&:hover': { 
                          bgcolor: alpha('#9c27b0', 0.05) 
                        }
                      }}
                    >
                      {row.map((cell: any, cellIndex: number) => (
                        <TableCell key={cellIndex} sx={{ fontSize: '0.875rem' }}>
                          {cell !== null && cell !== undefined ? String(cell) : ''}
                        </TableCell>
                      ))}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>

            <Divider sx={{ my: 3 }} />

            {/* 复制按钮 */}
            <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
              复制结果:
            </Typography>
            <Grid container spacing={2}>
              <Grid item xs={6} sm={3}>
                <Button 
                  variant="outlined" 
                  fullWidth
                  startIcon={<ContentCopyIcon />}
                  onClick={() => handleCopy('csv')}
                  sx={{ 
                    borderRadius: '20px',
                    textTransform: 'none',
                    fontWeight: 600
                  }}
                >
                  CSV
                </Button>
              </Grid>
              <Grid item xs={6} sm={3}>
                <Button 
                  variant="outlined"
                  fullWidth
                  startIcon={<ContentCopyIcon />}
                  onClick={() => handleCopy('markdown')}
                  sx={{ 
                    borderRadius: '20px',
                    textTransform: 'none',
                    fontWeight: 600
                  }}
                >
                  Markdown
                </Button>
              </Grid>
              <Grid item xs={6} sm={3}>
                <Button 
                  variant="outlined"
                  fullWidth
                  startIcon={<ContentCopyIcon />}
                  onClick={() => handleCopy('html')}
                  sx={{ 
                    borderRadius: '20px',
                    textTransform: 'none',
                    fontWeight: 600
                  }}
                >
                  HTML
                </Button>
              </Grid>
              <Grid item xs={6} sm={3}>
                <Button 
                  variant="outlined"
                  fullWidth
                  startIcon={<ContentCopyIcon />}
                  onClick={() => handleCopy('excel')}
                  sx={{ 
                    borderRadius: '20px',
                    textTransform: 'none',
                    fontWeight: 600
                  }}
                >
                  Excel
                </Button>
              </Grid>
            </Grid>
          </Paper>
        )}
      </Stack>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>

      {/* 成功提示 */}
      <Snackbar
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
      >
        <Alert severity="success" sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </ToolPageTemplate>
  );
};

export default JsonTablePage;
